import React, { useEffect, useState } from 'react';
import '../components.css';
import RepaymentScheduleService from '../../services/RepaymentScheduleService';
import { Link, useNavigate } from 'react-router-dom'; // 引入 useNavigate
import { 
  DeleteOutlined, 
  UpCircleOutlined, 
  SortAscendingOutlined, 
  SortDescendingOutlined, 
  PlusOutlined,
  DownloadOutlined,
  UploadOutlined,
  AppstoreOutlined,
  TableOutlined
} from '@ant-design/icons';
import {
  Table,
  Button,
  Popconfirm,
  Space,
  message,
  Input,
  Select,
  DatePicker,
  Tag,
  Dropdown,
  Menu,
  Card,
  Row,
  Col,
  Upload,
  Modal,
  Grid
} from 'antd';
import dayjs from 'dayjs';

const { Option } = Select;
const { RangePicker } = DatePicker;
const { useBreakpoint } = Grid;

// 状态映射
const STATUS_MAPPING = {
  PENDING: { text: '未到期', color: 'blue' },
  PAID: { text: '已支付', color: 'green' },
  OVERDUE: { text: '已逾期', color: 'red' }
};

export default function RepaymentScheduleList() {
  const [repaymentSchedules, setRepaymentSchedules] = useState([]);
  const [filteredData, setFilteredData] = useState([]);
  const [sortOrder, setSortOrder] = useState('ascend');
  const [loading, setLoading] = useState(false);
  const [viewMode, setViewMode] = useState('table'); // 'table' 或 'card'
  const screens = useBreakpoint();
  const navigate = useNavigate(); // 使用 useNavigate 创建 navigate 函数
  const [selectedRowKeys, setSelectedRowKeys] = useState([]); // 新增：选中的行的 ID

  // 查询条件状态
  const [searchKeyword, setSearchKeyword] = useState('');
  const [statusFilter, setStatusFilter] = useState('');
  const [dueDateRange, setDueDateRange] = useState(null);

  useEffect(() => {
    getAllRepaymentSchedules();
  }, []);

  const getAllRepaymentSchedules = () => {
    setLoading(true);
    RepaymentScheduleService.getAllRepaymentSchedules()
      .then((response) => {
        const formattedData = response.data.map(item => ({
          ...item,
          dueDate: dayjs(item.dueDate).format('YYYY-MM-DD')
        }));
        setRepaymentSchedules(formattedData);
        setFilteredData(formattedData);
        sortData(formattedData, 'contractNumber', 'ascend');
        setLoading(false);
      })
      .catch((error) => {
        console.log(error);
        message.error('加载还款计划失败');
        setLoading(false);
      });
  };

  // 排序函数
  const sortData = (data, field, order) => {
    const sortedData = [...data].sort((a, b) => {
      if (field === 'contractNumber' || field === 'period' || field === 'totalPeriods') {
        return order === 'ascend' ? a[field] - b[field] : b[field] - a[field];
      } else if (field === 'dueDate') {
        return order === 'ascend' 
          ? new Date(a[field]) - new Date(b[field])
          : new Date(b[field]) - new Date(a[field]);
      } else {
        return order === 'ascend'
          ? String(a[field]).localeCompare(String(b[field]))
          : String(b[field]).localeCompare(String(a[field]));
      }
    });
    setFilteredData(sortedData);
    setSortOrder(order);
  };

  // 处理排序
  const handleSort = (field, order) => {
    sortData(filteredData, field, order);
  };

  // 合同编号排序菜单
  const sortMenu = (
    <Menu>
      <Menu.Item key="contractNumberAsc" onClick={() => handleSort('contractNumber', 'ascend')}>
        <SortAscendingOutlined /> 合同编号升序
      </Menu.Item>
      <Menu.Item key="contractNumberDesc" onClick={() => handleSort('contractNumber', 'descend')}>
        <SortDescendingOutlined /> 合同编号降序
      </Menu.Item>
      <Menu.Item key="dueDateAsc" onClick={() => handleSort('dueDate', 'ascend')}>
        <SortAscendingOutlined /> 到期日升序
      </Menu.Item>
      <Menu.Item key="dueDateDesc" onClick={() => handleSort('dueDate', 'descend')}>
        <SortDescendingOutlined /> 到期日降序
      </Menu.Item>
      <Menu.Item key="customerNameAsc" onClick={() => handleSort('customerName', 'ascend')}>
        <SortAscendingOutlined /> 客户名称升序
      </Menu.Item>
      <Menu.Item key="customerNameDesc" onClick={() => handleSort('customerName', 'descend')}>
        <SortDescendingOutlined /> 客户名称降序
      </Menu.Item>
    </Menu>
  );

  const deleteRepaymentSchedule = (id) => {
    message.loading('删除中...', 0.5);
    setTimeout(() => {
      RepaymentScheduleService.deleteRepaymentSchedule(id)
        .then(() => {
          message.success('删除成功!');
          getAllRepaymentSchedules();
        })
        .catch((error) => {
          console.log(error);
          message.error('删除失败!');
        });
    }, 500);
  };

  const cancel = () => {
    message.info('已取消删除');
  };

  // 导出功能占位
  const exportToExcel = () => {
    message.info('导出功能已禁用');
  };

  // 导入功能占位
  const handleImport = () => {
    message.info('导入功能已禁用');
  };

  const handleSearch = () => {
    let result = [...repaymentSchedules];

    if (searchKeyword) {
      const keyword = searchKeyword.toLowerCase();
      result = result.filter(
        (item) =>
          (item.contractNumber?.toString().toLowerCase().includes(keyword)) ||
          (item.customerName?.toLowerCase().includes(keyword))
      );
    }

    if (statusFilter) {
      result = result.filter((item) => item.status === statusFilter);
    }

    if (dueDateRange && dueDateRange.length === 2) {
      const startDate = dueDateRange[0].startOf('day');
      const endDate = dueDateRange[1].endOf('day');
      result = result.filter((item) => {
        const date = item.dueDate ? new Date(item.dueDate) : null;
        return date && date >= startDate.toDate() && date <= endDate.toDate();
      });
    }

    sortData(result, 'contractNumber', sortOrder);
  };

  const handleReset = () => {
    setSearchKeyword('');
    setStatusFilter('');
    setDueDateRange(null);
    sortData(repaymentSchedules, 'contractNumber', sortOrder);
  };

  // 渲染卡片视图
  const renderCardView = () => {
    // 根据屏幕尺寸调整每行显示的卡片数量
    const cardSpan = screens.xxl ? 6 : screens.xl ? 8 : screens.lg ? 12 : 24;
    
    return (
      <Row gutter={[16, 16]} style={{ marginTop: 16 }}>
        {filteredData.map(item => (
          <Col span={cardSpan} key={item.id}>
            <Card 
              title={`合同: ${item.contractNumber}`} 
              bordered={false}
              style={{ borderRadius: 8, boxShadow: '0 2px 8px rgba(0,0,0,0.09)' }}
              extra={
                <Tag 
                  color={STATUS_MAPPING[item.status]?.color || 'default'}
                  style={{ borderRadius: '4px', fontWeight: 'bold' }}
                >
                  {STATUS_MAPPING[item.status]?.text || item.status}
                </Tag>
              }
            >
              <div style={{ marginBottom: 12 }}>
                <strong>客户: </strong>{item.customerName}
              </div>
              <div style={{ marginBottom: 12 }}>
                <strong>期数: </strong>{item.period}/{item.totalPeriods}
              </div>
              <div style={{ marginBottom: 12 }}>
                <strong>本金: </strong>¥{item.principal.toLocaleString()}
              </div>
              <div style={{ marginBottom: 16 }}>
                <strong>到期日: </strong>{item.dueDate}
              </div>
              <Space>
                <Button 
                  type="primary"
                  onClick={() => navigate(`/repaymentschedulelist/details/${item.id}`)}
                >
                  详情
                </Button>
                <Popconfirm
                  title="确定要删除该还款计划吗?"
                  description="此操作不可逆，请谨慎操作"
                  onConfirm={() => deleteRepaymentSchedule(item.id)}
                  onCancel={cancel}
                  okText="确定"
                  cancelText="取消"
                >
                  <Button type="danger">删除</Button>
                </Popconfirm>
              </Space>
            </Card>
          </Col>
        ))}
      </Row>
    );
  };

  const columns = [
    {
      title: (
        <Dropdown overlay={sortMenu} trigger={['click']}>
          <span style={{ cursor: 'pointer', display: 'flex', alignItems: 'center' }}>
            合同编号
            {sortOrder === 'ascend'
              ? <SortAscendingOutlined style={{ marginLeft: 8, color: '#1890ff' }} />
              : <SortDescendingOutlined style={{ marginLeft: 8, color: '#1890ff' }} />
            }
          </span>
        </Dropdown>
      ),
      dataIndex: 'contractNumber',
      key: 'contractNumber',
      align: 'center',
      width: 120
    },
    {
      title: '客户名称',
      dataIndex: 'customerName',
      key: 'customerName',
      align: 'center',
      width: 150
    },
    {
      title: '期数',
      key: 'period',
      align: 'center',
      render: (_, record) => `${record.period}/${record.totalPeriods}`,
      width: 100
    },
    {
      title: '本金',
      dataIndex: 'principal',
      key: 'principal',
      align: 'center',
      render: principal => `¥${principal.toLocaleString()}`,
      width: 120
    },
    {
      title: '到期日',
      dataIndex: 'dueDate',
      key: 'dueDate',
      align: 'center',
      render: dueDate => new Date(dueDate).toLocaleDateString(),
      width: 120
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      align: 'center',
      render: status => (
        <Tag
          color={STATUS_MAPPING[status]?.color || 'default'}
          style={{ borderRadius: '4px', fontWeight: 'bold' }}
        >
          {STATUS_MAPPING[status]?.text || status}
        </Tag>
      ),
      width: 100
    },
    {
      title: '操作',
      key: 'actions',
      align: 'center',
      fixed: 'right',
      width: 180,
      render: (_, record) => (
        <Space size="middle">
          <Button
            type="primary"
            onClick={() => navigate(`/repaymentschedulelist/details/${record.id}`)}
          >
            详情
          </Button>
          <Popconfirm
            title="确定要删除该还款计划吗?"
            description="此操作不可逆，请谨慎操作"
            onConfirm={() => deleteRepaymentSchedule(record.id)}
            onCancel={cancel}
            okText="确定"
            cancelText="取消"
          >
            <Button
              type="danger"
              icon={<DeleteOutlined />}
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  // 新增：处理行选择变化
  const onSelectChange = (newSelectedRowKeys) => {
    setSelectedRowKeys(newSelectedRowKeys);
  };

  // 新增：批量删除逻辑
  const batchDelete = () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请选择要删除的还款计划');
      return;
    }
    message.loading('批量删除中...', 0.5);
    setTimeout(() => {
      Promise.all(selectedRowKeys.map(id => RepaymentScheduleService.deleteRepaymentSchedule(id)))
        .then(() => {
          message.success('批量删除成功!');
          getAllRepaymentSchedules();
          setSelectedRowKeys([]);
        })
        .catch((error) => {
          console.log(error);
          message.error('批量删除失败!');
        });
    }, 500);
  };

  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };

  return (
    <div className="repayment-list-container">
      <Card
        title="还款计划管理"
        bordered={false}
        headStyle={{ fontSize: '18px', fontWeight: 'bold' }}
        style={{ borderRadius: '8px', boxShadow: '0 2px 8px rgba(0,0,0,0.1)' }}
        extra={
          <Space>
            <Dropdown overlay={sortMenu} trigger={['click']}>
              <Button icon={<SortAscendingOutlined />}>
                排序
              </Button>
            </Dropdown>
            <Button 
              type="primary" 
              icon={<DownloadOutlined />}
              onClick={exportToExcel}
            >
              导出
            </Button>
            <Button 
              icon={<UploadOutlined />}
              onClick={handleImport}
            >
              导入
            </Button>
            <Button 
              icon={viewMode === 'table' ? <AppstoreOutlined /> : <TableOutlined />}
              onClick={() => setViewMode(viewMode === 'table' ? 'card' : 'table')}
            >
              {viewMode === 'table' ? '卡片视图' : '列表视图'}
            </Button>
            <Link to="/AddRepaymentSchedule">
              <Button
                type="primary"
                icon={<PlusOutlined />}
                style={{
                  borderRadius: '4px',
                  backgroundColor: '#52c41a',
                  borderColor: '#52c41a'
                }}
              >
                添加计划
              </Button>
            </Link>
            <Popconfirm
              title="确定要批量删除选中的还款计划吗?"
              description="此操作不可逆，请谨慎操作"
              onConfirm={batchDelete}
              onCancel={cancel}
              okText="确定"
              cancelText="取消"
            >
              <Button
                type="danger"
                icon={<DeleteOutlined />}
              >
                批量删除
              </Button>
            </Popconfirm>
          </Space>
        }
      >
        <div className="list-header">
          <h2 style={{ marginBottom: '20px', color: '#1a3353' }}>还款计划列表</h2>

          {/* 查询栏 */}
          <Card 
            size="small" 
            style={{ marginBottom: '20px', borderRadius: '6px' }}
          >
            <Row gutter={[16, 16]} align="middle">
              <Col xs={24} sm={12} md={6}>
                <Input
                  placeholder="搜索合同/客户"
                  value={searchKeyword}
                  onChange={(e) => setSearchKeyword(e.target.value)}
                  allowClear
                  style={{ borderRadius: '4px' }}
                />
              </Col>
              
              <Col xs={24} sm={12} md={5}>
                <Select
                  value={statusFilter || undefined}
                  onChange={setStatusFilter}
                  placeholder="还款状态"
                  allowClear
                  style={{ width: '100%', borderRadius: '4px' }}
                >
                  <Option value="PENDING">未到期</Option>
                  <Option value="PAID">已支付</Option>
                  <Option value="OVERDUE">已逾期</Option>
                </Select>
              </Col>
              
              <Col xs={24} sm={18} md={8}>
                <RangePicker
                  value={dueDateRange}
                  onChange={setDueDateRange}
                  placeholder={['开始日期', '结束日期']}
                  style={{ width: '100%', borderRadius: '4px' }}
                />
              </Col>
              
              <Col xs={24} sm={6} md={5}>
                <Space>
                  <Button 
                    type="primary" 
                    onClick={handleSearch}
                    style={{ borderRadius: '4px' }}
                  >
                    搜索
                  </Button>
                  <Button 
                    onClick={handleReset}
                    style={{ borderRadius: '4px' }}
                  >
                    重置
                  </Button>
                </Space>
              </Col>
            </Row>
          </Card>
        </div>

        {/* 表格/卡片视图 */}
        {viewMode === 'table' ? (
          <Table
            columns={columns}
            dataSource={filteredData}
            bordered
            pagination={{ 
              pageSize: 10, 
              showSizeChanger: false,
              showTotal: total => `共 ${total} 条`,
              style: { marginTop: '16px' }
            }}
            rowKey="id"
            loading={loading}
            scroll={{ x: 'max-content' }}
            style={{ 
              borderRadius: '6px',
              boxShadow: '0 1px 4px rgba(0,0,0,0.05)'
            }}
            rowSelection={rowSelection} // 新增：启用行选择
          />
        ) : renderCardView()}
      </Card>
    </div>
  );
}